package com.atwisdom.star.core.bsl.planner.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.DateUtils;
import com.atwisdom.star.core.bsl.planner.MonthPlanBslService;
import com.atwisdom.star.core.bsl.planner.entity.SaleOrderSummary;
import com.atwisdom.star.core.dsl.modelClass.logic.Impl.LogicInstanceDslServiceImpl;
import com.atwisdom.star.exception.pojo.BusinessException;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Data
@Service
@NoArgsConstructor
public class MonthPlanBslServiceImpl implements MonthPlanBslService {

    private WorkCalendarBslServiceImpl workCalendarBslService;

    @Autowired
    public void setWorkCalendarBslService(WorkCalendarBslServiceImpl workCalendarBslService) {
        this.workCalendarBslService = workCalendarBslService;
    }

    private LogicInstanceDslServiceImpl logicInstanceDslService;

    @Autowired
    public void setLogicInstanceDslService(LogicInstanceDslServiceImpl logicInstanceDslService) {
        this.logicInstanceDslService = logicInstanceDslService;
    }

    //销售订单按背番、发货日期分组发货量汇总数据列表
    private List<SaleOrderSummary> saleOrderSummaryList = new ArrayList<>();

    /**
     * 初始化月内示计划MRP的基础数据
     */
    public void initMonthPlanMRP(JSONObject dataObj) {
        JSONObject param = dataObj.getJSONObject("param");
        String yearMonth = param.getString("yearMonth");
        if(StringUtils.isBlank(yearMonth)){
            String msg = "在月内示计划计算参数中，月内示年月（yyyy-MM）不能为空";
            throw new BusinessException("999999", msg);
        }

//        Date startTime = param.getDate("startTime");
//        Date endTime = param.getDate("endTime");
//        LocalDate startLocalDate = DateUtils.ConvertDateToLocalDate(startTime);
//        int startYear = startLocalDate.getYear();
//        int startMonth = startLocalDate.getMonthValue();
//
//        LocalDate endLocalDate = DateUtils.ConvertDateToLocalDate(endTime);
//        int endYear = endLocalDate.getYear();
//        int endMonth = endLocalDate.getMonthValue();
//
//        String msg;
//        if (startLocalDate.isAfter(endLocalDate)) {
//            msg = "在月内示计划计算参数中，开始日期不能大于结束日期";
//            throw new BusinessException("999999", msg);
//        }
//
//        if (startYear != endYear || startMonth != endMonth) {
//            msg = "在月内示计划计算参数中，开始日期年月必须等于结束日期的年月";
//            throw new BusinessException("999999", msg);
//        }

        this.initMonthPlan(yearMonth);
    }

    @Override
    public void initMonthPlan(String yearMonth) {
        String[] ymAry = yearMonth.split("-");
        int year = Integer.valueOf(ymAry[0]);
        int month = Integer.valueOf(ymAry[1]);
        this.saleOrderSummaryList = new ArrayList<>();
        String condition = "yearMonth='" + yearMonth + "'";
        List<JSONObject> monthPlanList = logicInstanceDslService.query(condition, "MonthPlan", null);
        for (JSONObject jsonObject : monthPlanList) {
            JSONObject hier = jsonObject.getJSONObject("hier");
            JSONArray content = hier.getJSONArray("content");
            for (int i = 0; i < content.size(); i++) {
                JSONObject contentJson = (JSONObject) content.get(i);
                String nodeId = contentJson.getString("nodeId");
                if (nodeId.equalsIgnoreCase("root")) {
                    continue;
                }
                JSONObject values = contentJson.getJSONObject("values");
                String materialBCode = values.getString("material_bcode");
                int quantity = values.getInteger("quantity");
                int workDay = this.workCalendarBslService.getWorkDay(year, month);
                int avg = (int) Math.ceil(quantity / workDay);

                SaleOrderSummary saleOrderSummary = new SaleOrderSummary();
                saleOrderSummary.setYearMonth(yearMonth);
                saleOrderSummary.setMaterialBCode(materialBCode);
                saleOrderSummary.setSaleQuantity(avg);
                saleOrderSummary.setOrderType(1);
                saleOrderSummary.setWorkDay(workDay);
                saleOrderSummary.setTotalQuantity(quantity);
                this.saleOrderSummaryList.add(saleOrderSummary);
            }
        }
    }
}
